package com.springboot.springmvc.restful.crud.controller;

import com.springboot.springmvc.restful.crud.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;

//异常案例；@ExceptionHandler
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public R hello(@RequestParam(value = "i",defaultValue = "0") Integer i){
        Integer j = 10/i;
        return R.success(i);
    }
    /*
    如果Controller出现异常，则在类中自动寻找有@ExceptionHandler的方法
            若有，则执行该方法，其返回值就是客户端收到的结果
    */

    @ExceptionHandler(ArithmeticException.class)
    public R handleException01(Exception e){
        System.out.println("【本类】-ArithmeticException");
        return R.error(100,"执行异常" + e.getMessage());
    }
    @ExceptionHandler(FileNotFoundException.class)
    public R handleException02(FileNotFoundException e){
        System.out.println("【本类】-FileNotFoundException");
        return R.error(200,"文件不存在" + e.getMessage());
    }
    @ExceptionHandler(Throwable.class)
    public R handleException02(Throwable e){
        return R.error(500,"其他异常" + e.getMessage());
    }
}
